"""
Author: Meng
Date: 2018/8/17
"""

import os
import json
import psutil


class MSsr:
    def __init__(self):
        self.path = '/etc/shadowsocks.json'
        self.log_path = '/var/log/shadowsocks.log'
        self.start_ss_cmd = 'ssserver -c /etc/shadowsocks.json -d start'
        self.restart_ss_cmd = 'ssserver -c /etc/shadowsocks.json -d restart'
        self.stop_ss_cmd = 'ssserver -c /etc/shadowsocks.json -d stop'
        self.config = self._read_config()

    def _read_config(self):
        with open(self.path) as f:
            data = f.read()
        data = json.loads(data)
        return data

    @staticmethod
    def _modification_log(data:list):
        new_list = []
        for item in data:
            if 'INFO' in item:
                new_list.append({'level': '', 'log': item})
            elif 'WARNING' in item:
                new_list.append({'level': 'warning', 'log': item})
            elif 'ERROR' in item:
                new_list.append({'level': 'danger', 'log': item})
            else:
                new_list.append({'level': 'info', 'log': item})
        return new_list

    def restart_server(self):
        p = os.popen(self.restart_ss_cmd)
        s = p.read()
        return s

    def stop_server(self):
        p = os.popen(self.stop_ss_cmd)
        s = p.read()
        return s

    def get_server_status(self):
        all_process = psutil.process_iter()
        status = 0
        for process in all_process:
            if 'ssserver' in process.name():
                status = 1
        return 'running' if status == 1 else 'stop'

    def get_server_log(self, now_line):
        # 读取文件遇到decode错误时忽略
        with open(self.log_path, encoding='utf8', errors='ignore') as f:
            logs = f.readlines()
        lines = len(logs)
        if now_line:
            data = logs[now_line:]
            return lines, self._modification_log(data)
        data = logs[-50:]
        return lines, self._modification_log(data)

    def get_user_list(self):
        if self.config:
            users = self.config.get('port_password')
            users_list = [{'port': key, 'pwd': users.get(key)} for key in users.keys()]
            return users_list
        return []

    def update_user_list(self, users_list):
        if self.config:
            try:
                users = {}
                for item in users_list:
                    users[str(item.get('port'))] = item.get('pwd')
                self.config['port_password'] = users
                data = json.dumps(self.config)
                with open(self.path, 'w', encoding='utf8') as f:
                    f.write(data)
                p = os.popen(self.restart_ss_cmd)
                s = p.read()
                return 1, s
            except Exception as e:
                return 0, str(e)


# if __name__ == '__main__':
#     MSsr().get_user_list()